package com.soloyogame.anitoys.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;


public class FileTool {
	public static String getExtention(String filePath) {
		int pos = filePath.lastIndexOf(".");
		String exname = filePath.substring(pos);
		return exname;
	}

	public static String getFileName(String filePath) {
		int pos = filePath.lastIndexOf("\\");
		return filePath.substring(pos);
	}
	
	/**
	 * 获取所有的文件,递归所有子目录
	 * @param paths
	 * @return
	 */
	public static List<File> getAllFilelist(String path) {
		List flist = new ArrayList();
		File d = new File(path);

		File[] lists = d.listFiles();
		
		if(lists!=null){
			for (int i = 0; i < lists.length; i++) {
				if (lists[i].isFile()) {
					flist.add(lists[i]);
				}
				//如果是目录,递归获取其下所有文件
				else if(lists[i].isDirectory()){
					flist.addAll(FileTool.getAllFilelist(lists[i].getPath()));
				}
	
			}
		}
		return flist;

	}

	public static List<File> getfilelist(String paths) {
		List flist = new ArrayList();
		File d = new File(paths);

		File[] lists = d.listFiles();
		
		if(lists!=null){
			for (int i = 0; i < lists.length; i++) {
				if (lists[i].isFile()) {
					flist.add(lists[i]);
				}
	
			}
		}
		return flist;

	}

	public static List getDirlist(String paths) {
		List l1 = new ArrayList();
		File d = new File(paths);

		File lists[] = d.listFiles();

		for (int i = 0; i < lists.length; i++) {
			if (lists[i].isDirectory()) {
				l1.add(lists[i].getName().toString());
			}

		}
		return l1;

	}

	public static void deleteFile(String dir) {
		File d = new File(dir);
		File lists[] = d.listFiles();

		for (int i = 0; i < lists.length; i++) {
			if (lists[i].isFile()) {
				lists[i].delete();
			}

		}
	}
	public static void deleteFileByPath(String filePath) {
		File d = new File(filePath);
		d.delete();
		
	}
	public static void renameFile(String name1,String name2) {
		File newFile=new File(name2);
		File d = new File(name1);
		d.renameTo(newFile);
	}

	public static void deleteFile(String dirPath, String filename) {
		File d = new File(dirPath);
		File lists[] = d.listFiles();

		for (int i = 0; i < lists.length; i++) {
			if (lists[i].getName().equals(filename))

				lists[i].delete();

		}
	}

	public static void deletedir(String dirPath) {
		File d = new File(dirPath);
		File lists[] = d.listFiles();
		for (int i = 0; i < lists.length; i++) {

			if (lists[i].isDirectory()) {
				String p = lists[i].getAbsolutePath();
				File f1 = new File(p);
				//System.out.println(f1);
				f1.delete();
				try {
					Runtime.getRuntime().exec("rd " + p + "  /s /q");
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

	}

	public static void saveObjectToFile(Object obj, String filepath) {
		ObjectOutputStream out = null;
		try {
			out = new ObjectOutputStream(new FileOutputStream(filepath));
			out.writeObject(obj);
			//System.out.println("save object success");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.flush();
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

	/**
	 * 插入行
	 * 
	 * @param filePath
	 * @param lines
	 * @throws IOException
	 */
	public static void addLine(String filePath, String line) throws IOException {
		BufferedWriter bw = null;
		bw = new BufferedWriter(new FileWriter(filePath, true));
		bw.write(line);
		bw.newLine();
		bw.flush();
		bw.close();

	}

	public static Object getObjectFromFile(String filepath) {
		Object obj = null;
		ObjectInputStream in = null;
		try {
			in = new ObjectInputStream(new FileInputStream(filepath));
			obj = in.readObject();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return obj;
	}

	public static void saveStringToFile(String s, String filepath) {
		DataOutputStream out = null;
		FileOutputStream is=null;
		try {
			is=new FileOutputStream(filepath);
			out = new DataOutputStream(is);
			byte[] bytes = s.getBytes("UTF-8");
			out.write(bytes);
			//System.out.println("save String success");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.flush();
					out.close();
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

	public static void saveStringToFile(String s, String filepath, String encode) {
		DataOutputStream out = null;
		FileOutputStream is=null; 
		try {
			is=new FileOutputStream(filepath);
			out = new DataOutputStream(is);
			byte[] bytes = s.getBytes(encode);
			out.write(bytes);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.flush();
					out.close();
					is.close(); 
					is.flush();
					
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

	public static void saveBytesToFile(byte[] bytes, String filepath) {
		DataOutputStream out = null;
		FileOutputStream is=null;
		try {
			is=new FileOutputStream(filepath);
			
			out = new DataOutputStream(is);
			out.write(bytes);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.flush();
					out.close();
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

	public static String readFile(String filePath) {
		String encode = FileTool.getEncode(filePath);
		String str = "";
		FileInputStream in = null;
		InputStreamReader isr = null;
		BufferedReader reader = null;
		try {
			in = new FileInputStream(filePath);
			isr = new InputStreamReader(in, encode);
			reader = new BufferedReader(isr);
			String tempStr;
			while ((tempStr = reader.readLine()) != null) {
				str = str + tempStr+"\n";
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (isr != null) {
				try {
					isr.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return str;
	}

	public static String changeEncode(String string, String code) {
		byte[] bt = string.getBytes();
		try {
			string = new String(bt, code);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return string;
	}

	public static void createFolder(String folderPath) {
		String filePath = folderPath;
		java.io.File myFile = new java.io.File(filePath);
		try {
			if (myFile.isDirectory()) {
			} else {
				myFile.mkdirs();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 判断文件是否存在
	 * 
	 * @param filePath
	 * @return
	 */
	public static boolean isExist(String filePath) {
		boolean result = false;
		java.io.File myFile = new java.io.File(filePath);
		try {
			if (myFile.isFile() || myFile.isDirectory() || myFile.isHidden()) {
				result = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	public static byte[] readFileBytes(String path) throws Exception{
		byte[] content=null;
		int BUFFER_SIZE=8096;
        InputStream fis = new BufferedInputStream(new FileInputStream(path));
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try{
       
        byte[] buf = new byte[BUFFER_SIZE];
        int size = 0;
        while ((size = fis.read(buf)) != -1){
       	
        	out.write(buf, 0, size);
        }
        
        content = out.toByteArray();
        }
        catch(Exception e){
        	e.printStackTrace();
        }
        finally{
        fis.close();
        out.close();
        }
        return content;
	}

	public static byte[] getBytes(File file) throws IOException {

		InputStream is = null;
		byte[] bytes = null;
		try {
			// 获取文件大小
			is = new FileInputStream(file);
			long length = file.length();
			if (length > Integer.MAX_VALUE) {
				// 文件太大，无法读取
				throw new IOException("File is to large " + file.getName());
			}
			// 创建一个数据来保存文件数据
			bytes = new byte[(int) length];
			// 读取数据到byte数组中
			int offset = 0;
			int numRead = 0;
			while (offset < bytes.length

			&& (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {

				offset += numRead;

			}
			// 确保所有数据均被读取

			if (offset < bytes.length) {

				throw new IOException("Could not completely read file " + file.getName());

			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			is.close();
		}
		return bytes;

	}

	public static String getEncode(String filePath) {
		BytesEncodingDetect d = new BytesEncodingDetect();
		int i = d.detectEncoding(new File(filePath));
		return d.nicename[i];
	}

	/**
	 * 通过绝对路径,从根路径找起
	 * 
	 * @param absPath
	 * @return
	 */
	public static String getRealPath(String absPath) 
	{
		String realPath = null;

		// String realPath=FileTool.class.getResource(absPath).getPath();
		// LogTool.debug(FileTool.class,"realPath:"+ realPath);
		try 
		{
			realPath=FileTool.getRealPathFromWebRoot("/")+"/WEB-INF/classes/"+absPath;
			//realPath = new File(FileTool.class.getResource(absPath).toURI()).getPath();

		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		return realPath;
	}
	
	/**
	 * 通过绝对路径,从根路径找起
	 * @param absPath
	 * @return
	 */
	public static String getRealPathFromWebRoot(String absPath) 
	{
		String realPath = null;
		if(!absPath.startsWith("/"))
		{
			absPath="/"+absPath;
		}
		String webRoot=SpringTool.getServletContext().getRealPath("/"); 
		try 
		{
			realPath = webRoot+absPath;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return realPath;
	}
	
	

	public static void main(String args[]) throws Exception {
			String absPath="a/b/c";
			if(!absPath.startsWith("/")){
				absPath="/"+absPath;
			}
			System.out.println("absPath:"+absPath);
	}

}
